package serialize;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import utils.Log;

import java.io.IOException;

public class GsonTypeAdapterTest {

    enum ContentType {
        @SerializedName("0")
        ImageText(0),

        @SerializedName("1")
        Video(1);
        private int value;

        ContentType(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

    enum Number {
        A(1),B(2),C(3);
        int v;

        Number(int x) {
            v = x;
        }

    }

    @JsonAdapter(ContentTypeAdapter.class)
    static class BaseModel {
        int x;
        String y;
        Number z = Number.B;
        ContentType contentType = ContentType.ImageText;

        BaseModel(int x, String y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "BaseModel{" +
                    "x=" + x +
                    ", y='" + y + '\'' +
                    ", z=" + z +
                    ", contentType=" + contentType +
                    '}';
        }
    }

    static class ContentTypeAdapter extends TypeAdapter<BaseModel> {
        @Override
        public void write(JsonWriter jsonWriter, BaseModel base) throws IOException {
            jsonWriter.beginObject();
            jsonWriter.name("x").value(base.x);
            jsonWriter.name("y").value(base.y);
            if (base.z != null) {
                jsonWriter.name("z").value(base.z.v);
            }

            if (base.contentType != null) {
                jsonWriter.name("contentType").value(base.contentType.getValue());
            }
        }


        @Override
        public BaseModel read(JsonReader jsonReader) throws IOException {
            return null;
        }
    }


    public static void main(String[] args) throws Exception {
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(BaseModel.class, new ContentTypeAdapter());
        final Gson gson = gsonBuilder.create();

        BaseModel base = new BaseModel(1, "2");
        String str = gson.toJson(base);
        Log.vn(str);
    }

}
